# 构建阶段：安装依赖
FROM python:3.9-slim AS builder

# 设置工作目录
WORKDIR /app

# 安装构建依赖
RUN apt-get update && \
    apt-get install -y --no-install-recommends \
    gcc \
    default-libmysqlclient-dev \
    pkg-config \
    && rm -rf /var/lib/apt/lists/*

# 复制requirements文件
COPY requirements.txt .

# 创建虚拟环境并安装依赖
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
RUN pip install --no-cache-dir --upgrade pip && \
    pip install --no-cache-dir -r requirements.txt

# 最终阶段：创建运行环境
FROM python:3.9-slim

# 设置工作目录
WORKDIR /app

# 设置时区为东八区
ENV TZ=Asia/Shanghai
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone

# 安装运行时依赖
RUN apt-get update && \
    apt-get install -y --no-install-recommends \
    default-libmysqlclient-dev \
    cron \
    curl \
    dos2unix \
    && rm -rf /var/lib/apt/lists/*

# 从构建阶段复制虚拟环境
COPY --from=builder /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"

# 复制项目文件
COPY . .

# 创建必要的目录并设置权限
RUN mkdir -p logs user_scripts && \
    dos2unix start_with_init.sh && \
    chmod +x start_with_init.sh

# 安装MySQL客户端和Redis客户端（用于健康检查）
RUN apt-get update && \
    apt-get install -y --no-install-recommends \
    default-mysql-client \
    redis-tools \
    && rm -rf /var/lib/apt/lists/*

# 暴露端口
EXPOSE 5000 5001 5002 5013

# 默认命令
CMD ["./start_with_init.sh"]